package com.taptech.doufu.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.bean.cp.CpBean;
import com.taptech.doufu.R;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.presenter.home.TagGovernmentPresenter;
import com.taptech.doufu.services.CpService;
import com.taptech.doufu.services.NovelCreateServices;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.DiaobaoUtil;
//import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.NotifyUtil;
import com.taptech.doufu.ui.view.NovelAptitudeDialog;
import com.taptech.doufu.ui.view.NovelOriginalDialog;
import com.taptech.doufu.ui.view.NovelPublishDialog;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by op0509 on 2016/5/17.
 */
public class NovelCreateTosActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener,
        NovelPublishDialog.PublishTypeSelectListener, NovelOriginalDialog.OriginalTypeSelectListener, NovelAptitudeDialog.AptitudeTypeSelectListener, TextWatcher {
    private WaitDialog dialog;
    private TextView tvSure;
    /** 作品名称 */
    private EditText etName;
    private ImageView imgNameHelp;
    /** 标签, 发表方式，原创性， 性向 */
    private TextView tvPublish, tvAptitude,tvTipAboutSex;
    /**
     * 标签集合
     */
    private HashMap<Integer, String> govermentTags = new HashMap<>();  //官方标签
    private ArrayList<String> tagsList;   //自定义标签
    private RelativeLayout rlTag;
    private CpBean cpBean;

    private int typePublishNum, typeAptitudeNum;
    private String tongOriginal, aptitudeNameA, aptitudeNameB;

    private TextView tvTags,tvTagTitle;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addShadeBg();
        setContentView(R.layout.activity_novel_create_tos);
        initUI();
        initTags();
        setTageIsTrue();
    }

    private void initUI() {
        tvSure = (TextView) findViewById(R.id.tv_novel_create_tos_sure);
        tvSure.setOnClickListener(this);
        findViewById(R.id.rl_activity_novel_create_tos_publish).setOnClickListener(this);
        findViewById(R.id.rl_activity_novel_create_tos_aptitude).setOnClickListener(this);
        etName = (EditText) findViewById(R.id.et_activity_novel_create_ed_name);
        etName.addTextChangedListener(this);
        imgNameHelp = (ImageView) findViewById(R.id.img_novel_create_name);
        imgNameHelp.setOnClickListener(this);
        tvAptitude = (TextView) findViewById(R.id.tv_activity_novel_create_tos_aptitude);
        tvTipAboutSex = (TextView) findViewById(R.id.tvTipAboutSex);
        tvPublish = (TextView) findViewById(R.id.tv_activity_novel_create_tos_publish);
        rlTag = (RelativeLayout) findViewById(R.id.rl_activity_novel_create_tos_tag);
        rlTag.setOnClickListener(this);
        tvTags = (TextView) findViewById(R.id.tvTags);
        tvTagTitle = (TextView) findViewById(R.id.tvTagTitle);
    }

    private void initTags()
    {
        tagsList = new ArrayList<>();
        intTagFromNewCpDes();
    }

    private void intTagFromNewCpDes()
    {
        tagsList.clear();
        cpBean = (CpBean) getIntent().getSerializableExtra(Constant.TAG);
        if (cpBean != null)
        {
            tagsList.add(cpBean.getName());
        }
        updateTags();
        setTagAddBac();
    }


    private void updateTags() {
        StringBuilder sb = new StringBuilder();
        if (govermentTags != null && govermentTags.values()!=null) {

            for (String tag: govermentTags.values()) {
                sb.append(tag).append("-");
            }
        }
        if (tagsList != null) {
            for (int i = 0; i < tagsList.size(); i++)
            {
                sb.append(tagsList.get(i)).append("-");
            }
        }
        String str = "";
        if (sb.length() > 0) {
            str = sb.substring(0,sb.length()-1);
        }
        tvTags.setText(str);
    }

    private void setTagAddBac()
    {
        if (tagsList.size()+govermentTags.size() == 0)
        {
            if(tvSure.isEnabled() == true){
                tvSure.setEnabled(false);
                tvSure.setTextColor(getResources().getColor(R.color.novel_create_sure));
            }
        } else
        {
            setSureIsTrue();
        }
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (dialog != null && dialog.isShowing())
        {
            dialog.dismiss();
        }
        if (cpBean != null) //告诉服务器用户参与了这个标签的创建
        {
            CpService.getInstance().addUserTakeInTag(cpBean.getId(), this);
        }
        if (response.getStatus() == 0 && response.getFail_code() == 0) {
            JSONObject data = (JSONObject) response.getData();
            HomeTopBean bean = new HomeTopBean();
            bean.setJson2(data);
            bean.setArticle_num("");
            Toast.makeText(this,"创建小说成功",Toast.LENGTH_LONG).show();
            NotifyUtil.refrushMyNovelListNotify();
            Intent intent = new Intent(this, NovelCreatSecondActivity.class);
            intent.putExtra(Constant.NOVEL_ID, bean.getId());
            intent.putExtra(Constant.NOVEL_NAME, bean.getTitle());
            intent.putExtra(Constant.PRE_COLLECT_COUNT,bean.getPre_collect_count());
            startActivityForResult(intent, 10);
            finish();
        } else {
            Toast.makeText(this,DiaobaoUtil.getErrorTips(response),Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_activity_novel_create_tos_tag:
            {
                if (typeAptitudeNum > 0) {
                    Intent intent = new Intent(this,TagSelectActivity.class);
                    intent.putExtra(TagSelectActivity.INTENT_KEY_CUSTOM_TAG, tagsList);
                    intent.putExtra(TagSelectActivity.INTENT_KEY_GOVERMENT_TAG, govermentTags);
                    intent.putExtra(TagSelectActivity.INTENT_KEY_SEXUALITY,typeAptitudeNum);
                    startActivityForResult(intent,Constant.TAG_ADD_FROM_UGC);
                }else{
                    Toast.makeText(this, "需要先设置性向才可以设置标签",Toast.LENGTH_LONG).show();
                }
            }
            break;
            case R.id.rl_activity_novel_create_tos_publish:
                NovelPublishDialog dialogPublish = new NovelPublishDialog(this, R.style.UgcSweepDialog, typePublishNum, null, 0);
                dialogPublish.setOnPublishTypeSeleceListener(this);
                setDialogAttribute(dialogPublish);
                break;
            case R.id.rl_activity_novel_create_tos_aptitude:
                boolean hasSetTag = false;
                if (tagsList.size() + govermentTags.size() > 0) {
                    hasSetTag = true;
                }
                NovelAptitudeDialog dialogAptitude = new NovelAptitudeDialog(this, 1, R.style.UgcSweepDialog,hasSetTag, typeAptitudeNum, aptitudeNameA, aptitudeNameB, null);
                dialogAptitude.setAptitudeTypeSeleceListener(this);
                setDialogAttribute(dialogAptitude);
                break;
            case R.id.tv_novel_create_tos_sure:
                sure();
                break;
            case R.id.img_novel_create_name:
                BrowseActivity.startActivity(this, "http://api.doufu.la/index.php/journal/detail?id=63");
                break;
            default:
                break;
        }
    }

    private void setDialogAttribute(Dialog dialog){
        dialog.show();
        android.view.WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
    }

    public void back(View view)
    {
        finish();
    }

    @Override
    public void finish() {
        tagsList.clear();
        super.finish();
    }

    public void sure()
    {
        if (!isNovelName())
        {
            return;
        }
        if(isPublish()){
            Toast.makeText(this,"请选择发表方式",Toast.LENGTH_LONG).show();
//            UIUtil.toastMessage(this, "");
            return;
        }
        if(isAptitude()){
            Toast.makeText(this,"请选择性向",Toast.LENGTH_LONG).show();
            return;
        }
        if (tagsList.size()+govermentTags.size() < 1)
        {
            Toast.makeText(this,"最少填1个标签",Toast.LENGTH_LONG).show();
            return;
        }
        Log.d("tag", "已发送创建请求");
        dialog = new WaitDialog(this, R.style.updateDialog);
        dialog.show();
        NovelCreateServices.getInstance().saveTopicNovel(this, null, etName.getText().toString(), null, null, TagGovernmentPresenter.getAllTagList(tagsList,govermentTags), null, "", typeAptitudeNum+"", typePublishNum+"",
                "1", tongOriginal, aptitudeNameA, aptitudeNameB, null);
    }

    private boolean isNovelName()
    {
        String novelName = etName.getText().toString();
        if(DiaobaoUtil.getStringSizeNoSpace(novelName) <= 0){
            Toast.makeText(this,"请输入作品名称",Toast.LENGTH_LONG).show();
            return false;
        }else if(DiaobaoUtil.getStringSizeNoSpace(novelName) > 30){
            Toast.makeText(this,"作品名称不能超过30字",Toast.LENGTH_LONG).show();
            return false;
        }else{
            return true;
        }
    }

    private boolean isPublish(){
        String novelPublish = tvPublish.getText().toString();
        return TextUtils.isEmpty(novelPublish);
    }


    private boolean isAptitude(){
        String novelAptitude = tvAptitude.getText().toString();
        return TextUtils.isEmpty(novelAptitude);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.TAG_ADD_FROM_UGC)
        {
            if (data != null)
            {
                ArrayList<String> temp = (ArrayList<String>) data.getSerializableExtra(TagSelectActivity.INTENT_KEY_CUSTOM_TAG);
                if (temp != null) {
                    tagsList.clear();
                    ArrayList<String> dataTagList = temp;
                    tagsList.addAll(dataTagList);
                    setTagAddBac();
                }

                HashMap<Integer, String> tempMap = (HashMap<Integer, String>) data.getSerializableExtra(TagSelectActivity.INTENT_KEY_GOVERMENT_TAG);
                govermentTags = tempMap;
                updateTags();
                setSureIsTrue();
            }
        }
    }

    @Override
    public void selectListener(String typeName, int typeNum) {
        tvPublish.setText(typeName);
        typePublishNum = typeNum;
        setSureIsTrue();
    }

    @Override
    public void selectOriginalListener(String typeOriginal, int typeNum, String tongOrihinal) {
        this.tongOriginal = null;
        this.tongOriginal = tongOrihinal;
        setSureIsTrue();
    }

    @Override
    public void selectAptitudeTwoListener(String typeAptitudeOne, String typeAptitudeTwo, int typeNum) {
        tvAptitude.setText(getAptitudeName(typeNum));
        if (typeAptitudeNum != typeNum) {
            tagsList.clear();
            govermentTags.clear();
            tvTags.setText("");
        }
        typeAptitudeNum = typeNum;
        aptitudeNameA = null;
        aptitudeNameB = null;
        aptitudeNameA = typeAptitudeOne;
        aptitudeNameB = typeAptitudeTwo;
        setSureIsTrue();
        setTageIsTrue();
    }


    /**
     * 标签项要在性向选择之后选取
     */
    private void setTageIsTrue() {
        if (typeAptitudeNum > 0) {
            tvTipAboutSex.setVisibility(View.VISIBLE);
            //已选择性向
            tvTagTitle.setTextColor(getResources().getColor(R.color.novel_create_text));
        }else{
            tvTipAboutSex.setVisibility(View.GONE);
            //未选择性向
            tvTagTitle.setTextColor(getResources().getColor(R.color.novel_create_line_head_color));
        }
    }

    private String getAptitudeName(int typeNum){
        if(1 == typeNum){
            return "彩虹/BL";
        }else if(2 == typeNum){
            return "百合/GL";
        }else if(3 == typeNum){
            return "言情/BG";
        }else if(4 == typeNum){
            return "女尊/GB";
        }else{
            return "无CP、无性向";
        }
    }

    private void setSureIsTrue(){
        if(typePublishNum == 0 || typeAptitudeNum == 0 || TextUtils.isEmpty(etName.getText().toString().trim()) || tagsList.size()+govermentTags.size() < 1){
            return;
        }
        if(tvSure.isEnabled() == false){
            tvSure.setEnabled(true);
            tvSure.setTextColor(getResources().getColor(R.color.cfe6e6e));
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //Do Nothing
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() <= 0){
            if(tvSure.isEnabled() == true){
                tvSure.setEnabled(false);
                tvSure.setTextColor(getResources().getColor(R.color.novel_create_sure));
            }
        }else{
            setSureIsTrue();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        //Do Nothing
    }
}
